package com.gitee.security.handler;

import com.alibaba.fastjson.JSON;
import com.gitee.enums.ResponseEnum;
import com.gitee.security.validate.CaptchaException;
import com.gitee.vo.ResponseVo;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginFailHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (e instanceof BadCredentialsException || e instanceof UsernameNotFoundException) {
            response.getWriter().write(JSON.toJSONString(ResponseVo.error(ResponseEnum.USERNAME_PASSWORD_ERROR)));
        } else if (e instanceof CaptchaException) {
            response.getWriter().write(JSON.toJSONString(ResponseVo.error(e.getMessage())));
        } else {
            response.getWriter().write(JSON.toJSONString(ResponseVo.error(ResponseEnum.LOGIN_FAIL)));
        }
    }
}
